import React, { PureComponent } from "react";
import { Table, Modal } from "antd"; // Tooltip
import { connect } from "dva";
import dynamic from "umi/dynamic";
import {
  getMenuRouter,
  getPageOperate,
} from "components/layouts/menuFn";
import { openNotificationWithIcon } from "utils/comm";
import styles from "./index.less";

const AdvancedFilter = dynamic({ loader: async () => {
  return import("./components/AdvancedFilter");
} });

@connect(({ FlowConfigure, appListMenu, loading, Public }) => ({
  flowConfigStore: FlowConfigure,
  loading,
  menuAppStore: appListMenu,
  focusApp: appListMenu.focusApp,
  menuDataList: Public.menuDataList,
  resourceList: Public.resourceList,
}))
class FlowConfigureSelect extends PureComponent {
  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon;
    this.getMenuRouter = getMenuRouter.bind(this);
    this.getPageOperate = getPageOperate.bind(this);
    this.state = {
      page: {
        pageNum: 1,
        pageSize: 6,
      },
      selectedRows: [],
      totalCount: 0,
      datas: [],
    };
    this.rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({ selectedRows })
      },
    }
    this.baseQueryParam = {
      appId: "",
      busiId: "",
      tenantId: "",
      searchKey: "",
      timeStart: "", // 开始时间
      timeEnd: "", // 结束时间
      lastVersion : 1,
    };
    this.queryParams = this.baseQueryParam;
    this.columns = [
      {
        title: "流程模型名称",
        align: 'center',
        dataIndex: "modelName",
        key: "modelName",
        // width: '60px',
      },
      {
        title: "流程模型编码",
        align: 'center',
        dataIndex: "modelKey",
        key: "modelKey",
        // width: '60px',
        render: (v) => {
          return (
            <span
              title={v}
            >
              {v}
            </span>
          );
        },
      },
      {
        title: "版本号",
        align: 'center',
        dataIndex: "version",
        key: "version",
        // width: '35px',
      },
      // {
      //   title: "查看版本",
      //   align: 'center',
      //   width: '45px',
      //   dataIndex: "viewVersion",
      //   key: "viewVersion",
      //   render: (text, record) => {
      //     return (
      //       <div>
      //         <Link
      //           to={{
      //             pathname: "/flowmanage/flowconfigure/versionmanage",
      //             search: queryString.stringify({
      //               modelKey: record.modelKey,
      //             }),
      //           }}
      //         >
      //           版本历史
      //         </Link>
      //       </div>
      //     );
      //   },
      // },
      {
        title: "所属应用",
        align: 'center',
        dataIndex: "appName",
        key: "appName",
        // width: '45px',
        render: (v) => {
          return (
            <span
              title={v}
            >
              {v}
            </span>
          );
        },
      },
      {
        title: "状态",
        align: 'center',
        dataIndex: "category",
        key: "category",
        // width: '30px',
        render: (text, record) => {
         return record.category && this.getStatus(record.category)
        },
      },
      {
        title: "创建人",
        align: 'center',
        dataIndex: "creatorName",
        key: "creatorName",
        // width: '50px',
        render: (v) => {
          return (
            <span
              title={v}
            >
              {v}
            </span>
          );
        },
      },
      {
        title: "创建时间",
        align: 'center',
        dataIndex: "createTime",
        key: "createTime",
        // width: '80px',
        render: (v) => {
          return (
            <span
              title={v}
            >
              {v}
            </span>
          );
        },
      },
      {
        title: "修改人",
        align: 'center',
        dataIndex: "creatorName",
        key: "updateName",
        // width: '50px',
        render: (v) => {
          return (
            <span
              title={v}
            >
              {v}
            </span>
          );
        },
      },
      {
        title: "修改时间",
        align: 'center',
        dataIndex: "createTime",
        key: "updateTime",
        // width: '80px',
        render: (v) => {
          return (
            <span
              title={v}
            >
              {v}
            </span>
          );
        },
      },
    ];
  }

  componentDidMount() {
    this.isLeaf = false;
    this.initData();
  }

  componentWillUnmount() {
    this.isLeaf = true;
    // const { dispatch } = this.props;
    // dispatch({ type: "FlowConfigure/clearData" });
  }

  getStatus = (status) => {
    switch (status) {
      case "HISTORY":
        return (
          // <span className={cn(styles.status, styles.statusGrey)}>停用</span>
          <span>停用</span>
        );
      case "RUNNING":
        return (
          // <span className={cn(styles.status, styles.statusGreen)}>在线</span>
          <span>在线</span>
        );
      case "DESIGN":
        return (
          // <span className={cn(styles.status, styles.statusBlue)}>未发布</span>
          <span>未发布</span>
        );
      default:
        break;
    }
  };

  // 重置页面数据
  resetPageData = () => {
    this.queryParams = this.baseQueryParam;
    this.setState({
      page: { pageNum: 1, pageSize: 6 },
      datas: [],
      totalCount: 0,
    });
    if (this.QueryExtra) this.QueryExtra.handleReset();
    if (this.AdvancedFilter) this.AdvancedFilter.handleReset();
  };


  // 获取查询条件组件的this
  getRef = (type, _this) => {
    this[type] = _this;
  };

  // 获取查询参数
  getQueryParam = () => {
    const {
      page: { pageNum, pageSize },
    } = this.state;
    return { ...this.queryParams, pageNum, pageSize };
  };

  // 查询条件改变
  handleParamsChange = (item = {}) => {
    if(item.lastVersion === 0){
      delete this.queryParams.category
    }
    this.queryParams = { ...this.queryParams, ...item };
  };

  // 触发查询
  initData = () => {
    const { dispatch } = this.props;
    const params = this.getQueryParam();
    // if (!params.appId && !params.busiId && !params.tenantId) return;
    // dispatch({ type: "FlowConfigure/getFlowListData", payload: params });
    dispatch({ type: "Entrust/getListDataForEntrustData", payload: params }).then((res) => {
      // // eslint-disable-next-line no-debugger
      // debugger
      if(res.errCode === 0) {
        const { datas = {}, totalCount = 0 } = res
        this.setState({datas, totalCount})
      }
    })
  };

  handlePageChange = ({ current: pageNum, pageSize }) => {
    this.setState({ page: { pageNum, pageSize } }, () => {
      this.initData();
    });
  };

  // 搜索
  handleSearch = () => {
    const { page } = this.state;
    this.setState({ page: { ...page, pageNum: 1 } }, () => {
      this.initData();
    });
  };

  handleOk = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    const {selectedRows} = this.state
    const { handleClose } = this.props;
    if(selectedRows.length !== 1) {
      this.openNotificationWithIcon("warning", "", "请选择一条流程");
    } else {
      handleClose(selectedRows[0])
    }
  };

  handleCancel = () => {
    const { handleClose } = this.props;
    handleClose()
  };

  render() {
    const { loading, visible } = this.props;
    const {
      page: { pageNum, pageSize },
    } = this.state;
    const { datas = [], totalCount = 0 } = this.state;

    const listLoading =
      loading.effects["Entrust/getListDataForEntrustData"] || false;

    return (
      <Modal
        title="流程模型选择"
        visible={visible}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
        width="1000px"
        centered
        // confirmLoading={confirmLoading}
        destroyOnClose
      >
        <div className={styles.root}>
          <AdvancedFilter
            handleSearch={this.handleSearch}
            handleParamsChange={this.handleParamsChange}
            visible
            getRef={(_this) => this.getRef("AdvancedFilter", _this)}
          />
          <Table
            dataSource={datas}
            loading={listLoading}
            columns={this.columns}
            scroll={{x: 1200}}
            rowKey="modelId"
            bordered
            className={styles.spacing}
            onChange={this.handlePageChange}
            rowSelection={this.rowSelection}
            pagination={{
                    showQuickJumper: true,
                    showSizeChanger: true,
                    pageSizeOptions: ["6", "10", "20", "30"],
                    current: pageNum,
                    pageSize,
                    total: totalCount,
                  }}
          />
        </div>
      </Modal>
      
    );
  }
}

export default FlowConfigureSelect;
